package mcpclients

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/mark3labs/mcp-go/client"
	"github.com/mark3labs/mcp-go/client/transport"
	"github.com/mark3labs/mcp-go/mcp"
	"log"
	"strings"
	"time"
)

const (
	// ServerSSEApi mcp服务端的sse地址
	// modelscope服务参考: https://www.modelscope.cn/mcp/servers/@amap/amap-maps
	// 高德api-key配置参考: https://console.amap.com/dev/key/app
	ServerSSEApi = "https://mcp.api-inference.modelscope.net/f8690db6180c49/sse"
)

type WeatherInfo struct {
	City      string `json:"city"`
	Forecasts []struct {
		Date           string `json:"date"`
		Week           string `json:"week"`
		Dayweather     string `json:"dayweather"`
		Nightweather   string `json:"nightweather"`
		Daytemp        string `json:"daytemp"`
		Nighttemp      string `json:"nighttemp"`
		Daywind        string `json:"daywind"`
		Nightwind      string `json:"nightwind"`
		Daypower       string `json:"daypower"`
		Nightpower     string `json:"nightpower"`
		DaytempFloat   string `json:"daytemp_float"`
		NighttempFloat string `json:"nighttemp_float"`
	} `json:"forecasts"`
}

type WeatherRequest struct {
	City string `json:"city"`
}

// MCPWeatherClient 封装基于 mark3labs/mcp-go 的天气服务客户端
type MCPWeatherClient struct {
	mcpClient *client.Client // MCP 客户端实例
}

// NewMCPWeatherClient 初始化 MCP 天气服务客户端
func NewMCPWeatherClient() (*MCPWeatherClient, error) {
	// Create transport
	sseTransport, err := transport.NewSSE(ServerSSEApi)
	if err != nil {
		return nil, fmt.Errorf("无法连接到 MCP 服务器: %v", err)
	}

	// 初始化 MCP 客户端
	mcpClient := client.NewClient(sseTransport)
	cli := &MCPWeatherClient{
		mcpClient: mcpClient,
	}
	err = mcpClient.Start(context.Background())
	if err != nil {
		return nil, err
	}
	return cli, nil
}

// Close 关闭 MCP 客户端连接
func (c *MCPWeatherClient) Close() error {
	return c.mcpClient.Close()
}

// GetWeather 调用 MCP 天气服务获取指定城市的天气
func (c *MCPWeatherClient) GetWeather(ctx context.Context, city string) (string, error) {
	// 构造 MCP 服务调用请求
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	initRequest := mcp.InitializeRequest{}
	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
	initRequest.Params.ClientInfo = mcp.Implementation{
		Name:    "MCP Client - 天气服务",
		Version: "1.0.0",
	}
	initRequest.Params.Capabilities = mcp.ClientCapabilities{}
	serverInfo, err := c.mcpClient.Initialize(ctx, initRequest)
	if err != nil {
		log.Fatalf("Failed to initialize: %v", err)
	}
	log.Printf("ServerInfo: %#v\n", serverInfo)

	// 初始化服务成功,开始调用天气MCP服务:
	toolRequest := mcp.CallToolRequest{}
	toolRequest.Params.Name = "maps_weather"       // 调用工具的名称
	toolRequest.Params.Arguments = map[string]any{ // 调用工具的参数
		"city": city,
	}
	resp, err := c.mcpClient.CallTool(ctx, toolRequest)
	if err != nil {
		log.Fatalf("Failed to list directory: %v", err)
	}
	log.Printf("weatherInfoRes: %#v\n", resp)

	// 处理服务返回结果
	if resp.IsError {
		return "", fmt.Errorf("天气服务返回错误: result=%#v, content=%#v", resp.Result, resp.Content)
	}
	log.Printf("resp: %#v\n", resp)

	// 解析MCP返回的内容
	for _, content := range resp.Content {
		if textContent, ok := content.(mcp.TextContent); ok {
			var w WeatherInfo
			if err := json.Unmarshal([]byte(textContent.Text), &w); err != nil {
				return "", fmt.Errorf("天气服务返回错误,解析天气服务返回异常:%#v", err)
			}

			// 组装返回:
			respContent := strings.Builder{}
			respContent.WriteString("城市:" + w.City + "\n")

			for _, forecast := range w.Forecasts {
				respContent.WriteString(strings.Join([]string{
					"日期:" + forecast.Date,
					"白天天气:" + forecast.Dayweather,
					"白天温度:" + forecast.DaytempFloat + "℃",
					"白天风向:" + forecast.Daywind + "风",
					"白天风力:" + forecast.Daypower + "级",
					"夜间天气:" + forecast.Nightweather,
					"夜间温度:" + forecast.NighttempFloat + "℃",
					"夜间风向:" + forecast.Nightwind + "风",
					"夜间风力:" + forecast.Nightpower + "级",
				}, " "))
				respContent.WriteString("\n")
			}
			return respContent.String(), nil
		}
	}
	log.Printf("weather not found, weatherInfoRes: %#v\n", resp)
	return "", fmt.Errorf("%s", "天气服务返回错误: 未查询到天气信息") // resp.Result 为服务返回的天气信息（JSON格式或文本）

	// 返回结果参考
	/*&mcp.CallToolResult{
		Result: mcp.Result{
			Meta: map[string]interface{}(nil),
		},
		Content: []mcp.Content{
			mcp.TextContent{
				Annotated: mcp.Annotated{
					Annotations: (*mcp.Annotations)(nil),
				},
				Type: "text",
				Text: "{\n  \"city\": \"北京市\",\n  \"forecasts\": [\n    {\n      \"date\": \"2025-07-13\",\n      \"week\": \"7\",\n      \"dayweather\": \"晴\",\n      \"nightweather\": \"多云\",\n      \"daytemp\": \"36\",\n      \"nighttemp\": \"25\",\n      \"daywind\": \"东北\",\n      \"nightwind\": \"东北\",\n      \"daypower\": \"1-3\",\n      \"nightpower\": \"1-3\",\n      \"daytemp_float\": \"36.0\",\n      \"nighttemp_float\": \"25.0\"\n    },\n    {\n      \"date\": \"2025-07-14\",\n      \"week\": \"1\",\n      \"dayweather\": \"阴\",\n      \"nightweather\": \"雷阵雨\",\n      \"daytemp\": \"35\",\n      \"nighttemp\": \"24\",\n      \"daywind\": \"南\",\n      \"nightwind\": \"南\",\n      \"daypower\": \"1-3\",\n      \"nightpower\": \"1-3\",\n      \"daytemp_float\": \"35.0\",\n      \"nighttemp_float\": \"24.0\"\n    },\n    {\n      \"date\": \"2025-07-15\",\n      \"week\": \"2\",\n      \"dayweather\": \"雷阵雨\",\n      \"nightweather\": \"多云\",\n      \"daytemp\": \"30\",\n      \"nighttemp\": \"23\",\n      \"daywind\": \"东\",\n      \"nightwind\": \"东\",\n      \"daypower\": \"1-3\",\n      \"nightpower\": \"1-3\",\n      \"daytemp_float\": \"30.0\",\n      \"nighttemp_float\": \"23.0\"\n    },\n    {\n      \"date\": \"2025-07-16\",\n      \"week\": \"3\",\n      \"dayweather\": \"多云\",\n      \"nightweather\": \"晴\",\n      \"daytemp\": \"33\",\n      \"nighttemp\": \"24\",\n      \"daywind\": \"北\",\n      \"nightwind\": \"北\",\n      \"daypower\": \"1-3\",\n      \"nightpower\": \"1-3\",\n      \"daytemp_float\": \"33.0\",\n      \"nighttemp_float\": \"24.0\"\n    }\n  ]\n}",
			},
		},
		IsError: false,
	}*/
}
